import React, { useEffect, FC, useState } from 'react';
import { Modal } from 'antd';
import { useModel } from 'umi';
import classnames from 'classnames';

import styles from './index.less';
interface CommonModalType {
  type: string;
  wrapClassName?: string;
  okText?: string;
  cancelText?: string;
  onOk?: (cancelModel: () => void) => void;
  onCancel?: (cancelModel: () => void) => void;
  title?: string | React.ReactNode;
  [key: string]: any;
}

const CommonModal: FC<CommonModalType> = (props) => {
  const { type, wrapClassName, okText, cancelText, onOk, onCancel, ...rest } = props;
  const { title, visible, cancelModal } = useModel('useCommonModal', (model) => {
    let keys = Object.keys(model.visible);
    const needUpdate = keys[0] && keys.includes(type);
    const visible =
      (needUpdate && {
        visible: model.visible,
      }) ||
      undefined;

    return {
      ...visible,
      title: model.title,
      cancelModal: model.cancelModal,
    };
  });
  const [loading, setLoading] = useState(false);

  const _onOk = async () => {
    setLoading(true);
    if (typeof onOk === 'function') {
      await onOk(cancelModal);
    }
    setLoading(false);
  };
  const _onCancel = () => {
    onCancel ? onCancel(cancelModal) : cancelModal(type);
  };

  useEffect(() => {
    _onCancel();
    return () => {
      _onCancel();
    };
  }, []);
  let keys = Object.keys(visible || {});
  const needUpdate = keys[0] && keys.includes(type);

  if (needUpdate) {
    return (
      <Modal
        wrapClassName={classnames(styles['modal'], wrapClassName)}
        destroyOnClose={true}
        okText={okText || '确定'}
        centered={true}
        confirmLoading={loading}
        okButtonProps={{
          shape: 'round',
          className: styles['ok-button'],
        }}
        cancelButtonProps={{
          shape: 'round',
          className: styles['cancel-button'],
        }}
        cancelText={cancelText || '取消'}
        {...rest}
        title={title[type] || rest.title}
        visible={visible[type] || false}
        // afterClose={() => {
        //   // dispatch({ type: 'commonModal/clearVisiableItem', payload: type });
        // }}
        onOk={_onOk}
        onCancel={_onCancel}
      >
        {props.children}
      </Modal>
    );
  } else {
    return null;
  }
};
export default CommonModal;

// const wrapper = props => {
//   const { commonModal, type } = props;
//   const visible = (commonModal && commonModal.visible) || '';
//   let keys = Object.keys(commonModal.visible);
//   return <>{keys[0] && keys.includes(type) && <CommonModal {...props} />}</>;
// };

// export default connect(({ commonModal }) => {
//   return {
//     commonModal: commonModal,
//   };
// })(wrapper);
